const express = require("express");
const path = require("path")
const bodyParser = require('body-parser');
const multer = require('multer');
const formidable = require('formidable');
const cookieParser = require('cookie-parser')
const fs = require("fs");
const { Config } = require("./script/engine/config/Config");
const { Logger } = require("./script/engine/utils/Logger")
const { RedisUtil } = require("./script/engine/utils/RedisUtil")
const { DateUtil } = require("./script/engine/utils/DateUtil")
const { MySqlUtil } = require("./script/engine/utils/MySqlUtil")
const { Md5Helper } = require("./script/engine/utils/Md5Helper")
const { UserDao } = require("./script/game/dao/UserDao")
const http = require("http");
const https = require("https");

const child_process = require('child_process');

async function loadConfig() {
    return new Promise(async (resolve, reject) => {
        Logger.info("Config preload start")
        await Config.preload(path.resolve() + "/config/config.json");
        Logger.info("Config preload end")
        resolve();
    });
}

function getinfo(port, req, resp) {
    let result = {};
    let ip = req.headers['X-Real-IP'] || req.connection.remoteAddress
    if (ip.indexOf('::ffff:') != -1) {
        ip = ip.substring(7);
    }
    result["ip"] = ip;
    // result["AndroidUrl"] = Config.AndroidUrl
    // result["IOSUrl"] = Config.IOSUrl
    result["port"] = port

    resp.setHeader("Access-Control-Allow-Origin", "*");
    resp.end(JSON.stringify(result));
}

function handleClientLog(req, resp) {
    Logger.clientLog(req.body);
    resp.setHeader("Access-Control-Allow-Origin", "*");
    resp.end();
}

function upload(req, resp) {
    let baseUploadPath = path.resolve() + "/public/upload/";
    // Logger.log("upload========file====", req.file)
    let compressTime = DateUtil.now();
    baseUploadPath = path.join(baseUploadPath, compressTime.toString())
    // Logger.log("upload========baseUploadPath====", baseUploadPath)
    if (!fs.existsSync(baseUploadPath)) {
        fs.mkdirSync(baseUploadPath);
    }
    let result = {};
    if (req.file) {
        let fileName = req.file.originalname;
        // Logger.log("uploadimg========fileName====", fileName)
        let buffer = req.file.buffer;
        let mimetype = req.file.mimetype;
        // Logger.log("uploadimg========mimetype====", mimetype)
        // Logger.log("uploadimg========buffer====", buffer)
        let fileType = mimetype.split('/')[1];
        // Logger.log("uploadimg========fileType====", fileType)
        // let filePath = baseUploadPath + fileName
        let filePath = path.join(baseUploadPath, fileName)
        // Logger.log("uploadimg========filePath====", filePath)
        fs.writeFile(filePath, buffer, (err) => {
            // Logger.log("uploadimg========err==", err)
            if (err) {
                result["code"] = -1;
                result["msg"] = "保存文件失败再上传一次试试吧!";
                resp.end(JSON.stringify(result));
            } else {
                result["code"] = 0;
                result["msg"] = "上传成功"
                Logger.log("开始压缩=", baseUploadPath, fileName)
                PicCompress.compressPic(baseUploadPath, fileName, () => {
                    result["msg"] = "compress success"
                    result["url"] = filePath;

                    // let status = fs.statSync(filePath)
                    // Logger.log("status==", status)
                    let compressPicBuf = fs.readFileSync(filePath)
                    // Logger.log("compressPicBuf==", compressPicBuf)
                    result["mime"] = mimetype
                    result["size"] = compressPicBuf.length;
                    result["data"] = compressPicBuf.toString("base64")
                    resp.end(JSON.stringify(result));
                })
            }
        })

    } else {
        result["code"] = -1;
        result["msg"] = "file出现异常"
        resp.end(JSON.stringify(result));
    }
}

function convertwebp(req, resp) {
    let baseUploadPath = path.resolve() + "/public/convertwebp/";
    if (!fs.existsSync(baseUploadPath)) {
        fs.mkdirSync(baseUploadPath);
    }
    let ip = req.headers['X-Real-IP'] || req.connection.remoteAddress
    let body = req.body;
    if (!body) {
        Logger.warn("body is null", ip)
        return;
    }
    let encryKey = Md5Helper.getSimpleEncryptStr(body.time)
    if (encryKey != body.value) {
        Logger.warn("加密方式不对", ip, encryKey, body.value)
        return;
    }
    let compressTime = DateUtil.now();
    baseUploadPath = path.join(baseUploadPath, compressTime.toString())
    if (!fs.existsSync(baseUploadPath)) {
        fs.mkdirSync(baseUploadPath);
    }
    let result = {};
    if (req.file) {
        let fileName = req.file.originalname;
        Logger.log("uploadimg========req====", req)
        Logger.log("uploadimg========fileName====", fileName)
        let buffer = req.file.buffer;
        let mimetype = req.file.mimetype;
        Logger.log("uploadimg========mimetype====", mimetype)
        let fileType = mimetype.split('/')[1];
        Logger.log("uploadimg========fileType====", fileType)
        let filePath = path.join(baseUploadPath, fileName)
        fs.writeFile(filePath, buffer, (err) => {
            if (err) {
                result["code"] = -1;
                result["msg"] = "保存文件失败再上传一次试试吧!";
                resp.end(JSON.stringify(result));
            } else {
                result["code"] = 0;
                result["msg"] = "上传成功"
                let fileOnlyName = fileName.split(".")[0]
                Logger.log("platform=====", process.platform)
                if (process.platform == "darwin") { //mac
                    if (fileType == "gif") {
                        cmdPath = "./webplib/libwebp-1.0.3-mac-10.14/bin/gif2webp " + filePath + " -o " + baseUploadPath + "/" + fileOnlyName + ".webp"
                    } else {
                        cmdPath = "./webplib/libwebp-1.0.3-mac-10.14/bin/cwebp " + filePath + " -o " + baseUploadPath + "/" + fileOnlyName + ".webp"
                    }
                    // Logger.log("mac cmdPath==", cmdPath)
                } else if (process.platform == "linux") {
                    if (fileType == "gif") {
                        cmdPath = "./webplib/libwebp-1.0.3-linux-x86-64/bin/gif2webp " + filePath + " -o " + baseUploadPath + "/" + fileOnlyName + ".webp"
                    } else {
                        cmdPath = "./webplib/libwebp-1.0.3-linux-x86-64/bin/cwebp " + filePath + " -o " + baseUploadPath + "/" + fileOnlyName + ".webp"
                    }
                } else {

                    if (fileType == "gif") {
                        cmdPath = ".\\webplib\\libwebp-1.0.3-windows-x64\\bin\\gif2webp " + filePath + " -o " + baseUploadPath + "/" + fileOnlyName + ".webp"
                    } else {
                        cmdPath = ".\\webplib\\libwebp-1.0.3-windows-x64\\bin\\cwebp " + filePath + " -o " + baseUploadPath + "/" + fileOnlyName + ".webp"
                    }
                    // Logger.log("windows cmdPath==", cmdPath)
                }
                child_process.exec(cmdPath, (error, stdout, stderr) => {
                    if (error) {
                        Logger.log("转换失败", error);
                        return
                    }
                    // Logger.log("转换成功....", cmdPath);
                    let nowFilePath = baseUploadPath + "/" + fileOnlyName + ".webp"
                    let compressPicBuf = fs.readFileSync(nowFilePath)
                    result["mime"] = "image/webp"
                    result["newName"] = fileOnlyName + ".webp"
                    result["size"] = compressPicBuf.length;
                    result["data"] = compressPicBuf.toString("base64")
                    resp.end(JSON.stringify(result));
                });
            }
        })

    } else {
        result["code"] = -1;
        result["msg"] = "file出现异常"
        resp.end(JSON.stringify(result));
    }

}

function startWebServer() {
    let keyBasePath = path.resolve() + "/https"
    Logger.log("keyBasePath====", keyBasePath);

    const httpsOption = {
        key: fs.readFileSync(keyBasePath + "/sujiehao.club.key"),
        cert: fs.readFileSync(keyBasePath + "/sujiehao.club.crt")
    }
    for(let i=0; i<Config.WebPortList.length; i++){
        Logger.info("listent port=", Config.WebPortList[i])
        let app = express();
        let publicPath = path.resolve() + "/public"+Config.WebPortList[i];
        if (!fs.existsSync(publicPath)) {
            fs.mkdirSync(publicPath);
        }
        Logger.info("listent publicpath=", publicPath)
        app.use(bodyParser.urlencoded({ extended: false })); //解析post请求数据
        app.use(bodyParser.text()); // for parsing application/json
        app.use(bodyParser.json()); // for parsing application/json
        //设置静态网页目录
        let options = {
            setHeaders: function (res, path, stat) {
                res.set('Access-Control-Allow-Origin', '*')
            }
        }
        app.use(express.static(publicPath, options));
        app.use(cookieParser())
        app.all('*', function (req, res, next) {
            res.header("Access-Control-Allow-Origin", "*");//项目上线后改成页面的地址
            res.header("Access-Control-Allow-Headers", "X-Requested-With,Content-Type");
            res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
            next();
        });
        // app.post('/upload', multer().single('file'), upload);
        // app.use('/log', handleClientLog);
        app.post('/convertwebp', multer().single('file'), convertwebp);
        app.use('/getinfo', getinfo.bind(this, Config.WebPortList[i]));
        http.createServer(app).listen(Config.WebPortList[i]);
        Logger.info("startWebServer suc=", Config.WebPortList[i]);
    }
    // https.createServer(httpsOption, app).listen(Config.Web_Client_Port);
}

async function main() {
    await loadConfig();
    startWebServer();
}

main()